package com.hxk.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

import com.hxk.comm.MyAdaptableJobFactory;
import com.hxk.job.QuartzJob;

/**
 * 编写Quartz配置类
 * @author Cactus
 */
@Configuration
public class QuartzConfig {

	/**
	 * 创建job对象
	 */
	@Bean
	public JobDetailFactoryBean jobDetailFactoryBean() {
		JobDetailFactoryBean jobDetail = new JobDetailFactoryBean();
		//关联自定义job对象
		jobDetail.setJobClass(QuartzJob.class);
		return jobDetail;
	}
	
	/**
	 * 创建Trigger对象
	 * 简单的Trigger对象
	 */
	/*@Bean
	public SimpleTriggerFactoryBean simpleTriggerFactoryBean(JobDetailFactoryBean joFactoryBean) {
		SimpleTriggerFactoryBean triggerFactory = new SimpleTriggerFactoryBean();
		//关联job对象
		triggerFactory.setJobDetail(joFactoryBean.getObject());
		//设置执行时间
		//该参数表示一个执行的毫秒数
		triggerFactory.setRepeatInterval(2000);
		//重复次数
		triggerFactory.setRepeatCount(5);
		return triggerFactory;
	}*/
	
	/**
	 *  创建Scheduler对象
	 *  调用简单的Trigger对象
	 */
	/*@Bean
	public SchedulerFactoryBean schedulerFactoryBean(SimpleTriggerFactoryBean simpleTriggerFactoryBean) {
		SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
		//关联 trigger
		schedulerFactoryBean.setTriggers(simpleTriggerFactoryBean.getObject());
		return schedulerFactoryBean;
	}*/
	
	/**
	 * 创建Trigger对象
	 * 使用cron表达式方式
	 */
	@Bean
	public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean joFactoryBean) {
		CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
		bean.setJobDetail(joFactoryBean.getObject());
		bean.setCronExpression("0/2 * * * * ?");
		return bean;
	}
	/**
	 *  创建Scheduler对象
	 *  调用cron表达式方式的Trigger对象
	 */
	@Bean
	public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean cronTriggerFactoryBean, MyAdaptableJobFactory myAdaptableJobFactory) {
		SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
		//关联 trigger
		schedulerFactoryBean.setTriggers(cronTriggerFactoryBean.getObject());
		//修改job对象的工厂初始化类，处理在自定义QuartzJob中注入UserService报异常问题
		schedulerFactoryBean.setJobFactory(myAdaptableJobFactory);
		return schedulerFactoryBean;
	}
}
